package tools

import (
	"encoding/base64"
	"errors"
	"strings"
)

type URLDataType string

const (
	URLDataType_text_plain      URLDataType = "text/plain"      //文本数据
	URLDataType_text_html       URLDataType = "text/html"       //HTML代码
	URLDataType_text_css        URLDataType = "text/css"        //CSS代码
	URLDataType_text_javascript URLDataType = "text/javascript" //Javascript代码
	URLDataType_image_gif       URLDataType = "image/gif"       //base64编码的gif图片数据
	URLDataType_image_png       URLDataType = "image/png"       //base64编码的png图片数据
	URLDataType_image_jpeg      URLDataType = "image/jpeg"      //base64编码的jpeg图片数据
	URLDataType_image_x_icon    URLDataType = "image/x-icon"    //base64编码的icon图片数据
)

// 获取类型的文件后缀，不包含"."，没有的类型返回 "unknown"
func (t URLDataType) GetFileExtension() string {
	switch t {
	case URLDataType_text_plain:
		return "txt"
	case URLDataType_text_html:
		return "html"
	case URLDataType_text_css:
		return "css"
	case URLDataType_text_javascript:
		return "js"
	case URLDataType_image_gif:
		return "gif"
	case URLDataType_image_png:
		return "png"
	case URLDataType_image_jpeg:
		return "jpeg"
	case URLDataType_image_x_icon:
		return "icon"
	default:
		return "unknown"
	}
}

var BadURLDataTypeFormatError = errors.New("bad URL data scheme format!")

func URLDataTypeAll() []URLDataType {
	return []URLDataType{
		URLDataType_text_plain,
		URLDataType_text_html,
		URLDataType_text_css,
		URLDataType_text_javascript,
		URLDataType_image_gif,
		URLDataType_image_png,
		URLDataType_image_jpeg,
		URLDataType_image_x_icon,
	}
}

func DecodeURLData(urlData string) (data []byte, dataType URLDataType, err error) {
	if !strings.HasPrefix(urlData, "data:") {
		err = BadURLDataTypeFormatError
		return
	}
	urlData = urlData[5:]
	items := strings.Split(urlData, ",")
	if len(items) != 2 {
		err = BadURLDataTypeFormatError
		return
	}
	info := items[0]
	dataStr := items[1]
	isBase64Encode := strings.HasSuffix(info, ";base64")
	if isBase64Encode {
		info = info[:len(info)-7]
		data, err = base64.StdEncoding.DecodeString(dataStr)
	} else {
		data = []byte(dataStr)
	}
	dataType = URLDataType(info)
	return
}
